import * as vscode from 'vscode';
import { Snippet, SnippetManager } from '../utils/snippetManager';

export class InsertSnippetCommand {
    constructor(private snippetManager: SnippetManager) {}

    get commandId(): string {
        return 'snippetManager.insertSnippet';
    }

    async execute(snippet?: Snippet): Promise<void> {
        try {
            if (!snippet) {
                // 显示快速选择框
                const snippets = this.snippetManager.getAllSnippets();
                if (snippets.length === 0) {
                    vscode.window.showInformationMessage('No snippets available. Create one first!');
                    return;
                }

                const items = snippets.map(s => ({
                    label: s.name,
                    description: `${s.group} • ${s.description}`,
                    snippet: s
                }));

                const selected = await vscode.window.showQuickPick(items, {
                    placeHolder: 'Search and select a snippet to insert...',
                    matchOnDescription: true,
                    matchOnDetail: true
                });

                if (!selected) return;
                snippet = selected.snippet;
            }

            // 获取当前活动编辑器
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showErrorMessage('No active editor found');
                return;
            }

            // 插入代码片段
            await editor.edit(editBuilder => {
                const position = editor.selection.active;
                editBuilder.insert(position, snippet!.code);
            });

            // 格式化插入的代码
            await vscode.commands.executeCommand('editor.action.formatDocument');

        } catch (error) {
            vscode.window.showErrorMessage(`Failed to insert snippet: ${error}`);
        }
    }
}
